﻿using Expect.Core;
using WatiN.Core;
using System;

namespace Expect.WatiN
{
    /// <summary>
    /// Specification container for specs executed with WatiN
    /// </summary>
    public class WatiNSpecificationContainer : AbstractSpecificationContainer
    {
        /// <summary>
        /// Get the default browser
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        [STAThread]
        public virtual Browser GetBrowser(ExpectWatiNSection configuration)
        {
            if (configuration.Browser.ToLower() == "firefox")
            {
                return new FireFox(/*configuration.RootUrl*/);
            }

            return new IE(/*configuration.RootUrl*/true);
        }

        /// <summary>
        /// Method called after initializing tests
        /// </summary>
        [STAThread]
        public override void BeforeInit()
        {
            base.BeforeInit();
            var cfg = ExpectWatiNSection.Current;
            var browser = this.GetBrowser(cfg);
            if (browser is IE)
            {
                if (cfg.ClearCookies) (browser as IE).ClearCookies();
                if (cfg.ClearCache) (browser as IE).ClearCache();
                if (cfg.AutoClose) (browser as IE).AutoClose = true;
            }

            if (!string.IsNullOrEmpty(cfg.RootUrl))
            {
                browser.GoToNoWait(cfg.RootUrl);
            }

            Context.SetBrowser(browser);
        }

        /// <summary>
        /// Method called after teardown
        /// </summary>
        [STAThread]
        public override void AfterTeardown()
        {
            base.AfterTeardown();
            Context.Browser().Dispose();
            Context.SetBrowser(null);
        }
    }
}
